package com.tz.liveplayermodule;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.tz.liveplayermodule.downloadUtil.DownloadInfo;
import com.tz.liveplayermodule.greendao.db.DownloadInfoDao;
import com.tz.liveplayermodule.greendao.db.GreenDaoManager;
import com.tz.liveplayermodule.jcvideoplayer.JCVideoPlayer;
import com.tz.liveplayermodule.util.CommonUtils;
import com.tz.liveplayermodule.util.FileUtil;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class LocalVideoActivity extends Activity {
    private DownloadInfoDao downloadInfoDao;
    private TextView edit_text;
    boolean showChoose = false;
    private LocalVideoAdapter localVideoAdapter;
    private List<DownloadInfo> allDownloadInfoList;
    private List<DownloadInfo> baseDownloadInfoList;
    private List<DownloadInfo> downloadInfoList;
    private Map<String, List<DownloadInfo>> downloadInfoMap;
    private LinearLayout bottom_layout;
    private TextView choose_all, delete, title;
    private ListView local_video_list_view;
    private AlertDialog progressDialog;
    private boolean isBaseDate = true;
    private String chooseName;

    @SuppressLint("ResourceType")
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        if (savedInstanceState != null) {
            //如果系统回收的Activity， 但是系统却保留了Fragment， 当Activity被重新初始化， 此时， 系统保存的Fragment 的getActivity为空，
            //所以要移除旧的Fragment ， 重新初始化新的Fragment
            String FRAGMENTS_TAG = "android:support:fragments";
            savedInstanceState.remove(FRAGMENTS_TAG);
        }
        super.onCreate(savedInstanceState);

        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
//        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        setContentView(R.layout.activity_local_video);

        Window window = this.getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(getResources().getColor(R.color.yellow));

        title = (TextView) findViewById(R.id.title);

        findViewById(R.id.back_img).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (isBaseDate) {
                    finish();
                } else {
                    isBaseDate = true;
                    downloadInfoList.clear();
                    downloadInfoList.addAll(baseDownloadInfoList);
                    localVideoAdapter.notifyDataSetChanged();
                }
            }
        });
        edit_text = (TextView) findViewById(R.id.edit_text);
        local_video_list_view = (ListView) findViewById(R.id.local_video_list_view);
        bottom_layout = (LinearLayout) findViewById(R.id.bottom_layout);
        choose_all = (TextView) findViewById(R.id.choose_all);
        delete = (TextView) findViewById(R.id.delete);

        showDownload();
    }

    @Override
    public void onBackPressed() {
        if (isBaseDate) {
            finish();
        } else {
            isBaseDate = true;
            downloadInfoList.clear();
            downloadInfoList.addAll(baseDownloadInfoList);
            localVideoAdapter.notifyDataSetChanged();
        }
    }

    private void showDownload() {
        title.setText("离线缓存");

        allDownloadInfoList = new ArrayList<>();
        downloadInfoDao = GreenDaoManager.getInstance(this).getNewSession().getDownloadInfoDao();
        allDownloadInfoList.addAll(downloadInfoDao.queryBuilder()
                .where(DownloadInfoDao.Properties.CompleteType.eq("2")).list());

        downloadInfoMap = new HashMap<>();
        for (DownloadInfo downloadInfo : allDownloadInfoList) {
            if (downloadInfoMap.containsKey(downloadInfo.getClassName())) {
                List<DownloadInfo> downloadInfoList = downloadInfoMap.get(downloadInfo.getClassName());
                downloadInfoList.add(downloadInfo);
                downloadInfoMap.put(downloadInfo.getClassName(), downloadInfoList);
            } else {
                List<DownloadInfo> downloadInfoList = new ArrayList<>();
                downloadInfoList.add(downloadInfo);
                downloadInfoMap.put(downloadInfo.getClassName(), downloadInfoList);
            }
        }

        baseDownloadInfoList = new ArrayList<>();
        for (String key : downloadInfoMap.keySet()) {
            DownloadInfo downloadInfo = new DownloadInfo();
            downloadInfo.setClassName(key);
            downloadInfo.setClassId(downloadInfoMap.get(key).size() + "");
            baseDownloadInfoList.add(downloadInfo);
//            System.out.println("key==:" + key);
//            for (DownloadInfo downloadInfo : downloadInfoMap.get(key)) {
//                System.out.println("FileName" + downloadInfo.getFileName());
//            }
        }

        downloadInfoList = new ArrayList<>();
        downloadInfoList.addAll(baseDownloadInfoList);

        localVideoAdapter = new LocalVideoAdapter(this, downloadInfoList);
        local_video_list_view.setAdapter(localVideoAdapter);

        local_video_list_view.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @SuppressLint("WrongConstant")
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                if (edit_text.getText().toString().equals("编辑")) {
                    if (isBaseDate) {
                        //显示二级列表
                        isBaseDate = false;
                        downloadInfoList.clear();
                        chooseName = baseDownloadInfoList.get(i).getClassName();
                        for (DownloadInfo downloadInfo : allDownloadInfoList) {
                            if (downloadInfo.getClassName().equals(chooseName)) {
                                downloadInfoList.add(downloadInfo);
                            }
                        }
                        localVideoAdapter.notifyDataSetChanged();
                    } else {
                        //播放视频
                        String url = downloadInfoList.get(i).getUrl();
                        String filePath = downloadInfoList.get(i).getSavePath() + "/" + downloadInfoList.get(i).getFileId() + "." + url.substring(url.lastIndexOf(".") + 1);

//                        Intent intent = new Intent();
//                        intent.setAction(android.content.Intent.ACTION_VIEW);
//                        File file = new File(filePath);
//                        Uri uri;
//                        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
//                            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
//                            Uri contentUri = FileProvider.getUriForFile(LocalVideoActivity.this, "com.tz.liveplayermodule.fileprovider", file);
//                            intent.setDataAndType(contentUri, "video/*");
//                        } else {
//                            uri = Uri.fromFile(file);
//                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//                            intent.setDataAndType(uri, "video/*");
//                        }
//
//                        startActivity(intent);

                        File videoFile = new File(filePath);
                        if (videoFile.exists() && videoFile.isFile()) {
//                            Intent intent = new Intent(LocalVideoActivity.this, FullScreenPlayVideoActivity.class);
                            Intent intent = new Intent(LocalVideoActivity.this, FullScreenLiveVideoActivity.class);
                            intent.putExtra("filePath", filePath);
                            intent.setFlags(10001);
                            startActivity(intent);
//                            Uri videoUri = Uri.fromFile(videoFile);
//                            JCVideoPlayer.toFullscreenActivity(LocalVideoActivity.this, videoUri.getPath(), "", allDownloadInfoList.get(i).getFileName());
                        } else {
                            Toast.makeText(LocalVideoActivity.this, "该视频已不存在", Toast.LENGTH_LONG).show();
                        }

//                    Intent intent = new Intent(LocalVideoActivity.this, PlayVideoActivity.class);
//                    intent.putExtra("filePath", filePath);
//                    intent.putExtra("fileName", allDownloadInfoList.get(i).getFileName());
//                    startActivity(intent);
                    }
                } else {
                    //选择
                    if (downloadInfoList.get(i).isChoose()) {
                        downloadInfoList.get(i).setChoose(false);
                    } else {
                        downloadInfoList.get(i).setChoose(true);
                    }
                    localVideoAdapter.notifyDataSetChanged();
                    setBottomText();
                }
            }
        });

        edit_text.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (edit_text.getText().toString().equals("编辑")) {
                    edit_text.setText("取消");
                    showChoose = true;
                    bottom_layout.setVisibility(View.VISIBLE);
                } else {
                    edit_text.setText("编辑");
                    showChoose = false;
                    bottom_layout.setVisibility(View.GONE);
                    for (DownloadInfo downloadInfo : downloadInfoList) {
                        downloadInfo.setChoose(false);
                    }
                    setBottomText();
                }
                localVideoAdapter.notifyDataSetChanged();
            }
        });

        choose_all.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (choose_all.getText().toString().equals("全选")) {
                    for (DownloadInfo downloadInfo : downloadInfoList) {
                        downloadInfo.setChoose(true);
                    }
                } else {
                    for (DownloadInfo downloadInfo : downloadInfoList) {
                        downloadInfo.setChoose(false);
                    }
                }
                localVideoAdapter.notifyDataSetChanged();
                setBottomText();
            }
        });
        delete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                for (DownloadInfo downloadInfo : downloadInfoList) {
                    if (downloadInfo.isChoose()) {
                        if (isBaseDate) {
                            //TODO
                            List<DownloadInfo> downloadInfoList = downloadInfoMap.get(downloadInfo.getClassName());
                            for (DownloadInfo downloadInfo1 : downloadInfoList) {
                                String url = downloadInfo1.getUrl();
                                String filePath = downloadInfo1.getSavePath() + "/" + downloadInfo1.getFileId() + "." + url.substring(url.lastIndexOf(".") + 1);
                                FileUtil.delete(LocalVideoActivity.this, filePath);
                                downloadInfoDao.delete(downloadInfo1);
                            }
                        } else {
                            String url = downloadInfo.getUrl();
                            String filePath = downloadInfo.getSavePath() + "/" + downloadInfo.getFileId() + "." + url.substring(url.lastIndexOf(".") + 1);
                            FileUtil.delete(LocalVideoActivity.this, filePath);
                            downloadInfoDao.delete(downloadInfo);
                        }
                    }
                }

                allDownloadInfoList.clear();
                downloadInfoList.clear();
                downloadInfoMap.clear();
                baseDownloadInfoList.clear();

                downloadInfoDao = GreenDaoManager.getInstance(LocalVideoActivity.this).getNewSession().getDownloadInfoDao();
                allDownloadInfoList.addAll(downloadInfoDao.queryBuilder()
                        .where(DownloadInfoDao.Properties.CompleteType.eq("2")).list());

                downloadInfoMap = new HashMap<>();
                for (DownloadInfo downloadInfo : allDownloadInfoList) {
                    if (downloadInfoMap.containsKey(downloadInfo.getClassName())) {
                        List<DownloadInfo> downloadInfoList = downloadInfoMap.get(downloadInfo.getClassName());
                        downloadInfoList.add(downloadInfo);
                        downloadInfoMap.put(downloadInfo.getClassName(), downloadInfoList);
                    } else {
                        List<DownloadInfo> downloadInfoList = new ArrayList<>();
                        downloadInfoList.add(downloadInfo);
                        downloadInfoMap.put(downloadInfo.getClassName(), downloadInfoList);
                    }
                }

                for (String key : downloadInfoMap.keySet()) {
                    DownloadInfo downloadInfo = new DownloadInfo();
                    downloadInfo.setClassName(key);
                    downloadInfo.setClassId(downloadInfoMap.get(key).size() + "");
                    baseDownloadInfoList.add(downloadInfo);
                }

                if (isBaseDate) {
                    downloadInfoList.addAll(baseDownloadInfoList);
                } else {
                    downloadInfoList.clear();
                    for (DownloadInfo downloadInfo : allDownloadInfoList) {
                        if (downloadInfo.getClassName().equals(chooseName)) {
                            downloadInfoList.add(downloadInfo);
                        }
                    }
                }
                localVideoAdapter.notifyDataSetChanged();
            }
        });
    }

    private void setBottomText() {
        int chooseCount = 0;
        for (DownloadInfo downloadInfo : downloadInfoList) {
            if (downloadInfo.isChoose()) {
                chooseCount++;
            }
        }

        if (chooseCount == downloadInfoList.size()) {
            choose_all.setText("取消全选");
        } else {
            choose_all.setText("全选");
        }

        if (chooseCount == 0) {
            delete.setText("删除");
            delete.setTextColor(Color.parseColor("#FFBBBBBB"));
        } else {
            delete.setText("删除(" + chooseCount + ")");
            delete.setTextColor(Color.parseColor("#FFFF3F00"));
        }
    }


    public class LocalVideoAdapter extends BaseAdapter {
        private LayoutInflater mLayoutInflater;
        private List<DownloadInfo> mIntegralList;
        private Context mContext;
        private int mImgWidth, mImgHeight;

        public LocalVideoAdapter(Context context, List<DownloadInfo> integralList) {
            mLayoutInflater = LayoutInflater.from(context);
            mContext = context;
            mIntegralList = integralList;
        }

        @Override
        public int getCount() {
            return mIntegralList.size();
        }

        @Override
        public Object getItem(int i) {
            return null;
        }

        @Override
        public long getItemId(int i) {
            return 0;
        }

        @Override
        public View getView(final int i, View view, ViewGroup viewGroup) {
            ViewHolder holder;
            if (view == null) {
                view = mLayoutInflater.inflate(R.layout.item_local_video, null);
                holder = new ViewHolder();
                holder.choose_img = (ImageView) view.findViewById(R.id.choose_img);
//                holder.video_img = (ImageView) view.findViewById(R.id.video_img);
                holder.video_name = (TextView) view.findViewById(R.id.video_name);
//                holder.video_time = (TextView) view.findViewById(R.id.video_time);
                holder.video_size = (TextView) view.findViewById(R.id.video_size);
                view.setTag(holder);
            } else {
                holder = (ViewHolder) view.getTag();
            }
            if (showChoose) {
                holder.choose_img.setVisibility(View.VISIBLE);
            } else {
                holder.choose_img.setVisibility(View.GONE);
            }
            if (mIntegralList.get(i).isChoose()) {
                holder.choose_img.setImageResource(R.mipmap.choose);
            } else {
                holder.choose_img.setImageResource(R.mipmap.not_choose);
            }

            if (isBaseDate) {
                holder.video_name.setText(mIntegralList.get(i).getClassName());
                holder.video_size.setText("已缓存：" + mIntegralList.get(i).getClassId() + "个");
            } else {
                String url = mIntegralList.get(i).getUrl();
                String filePath = mIntegralList.get(i).getSavePath() + "/" + mIntegralList.get(i).getFileId() + "." + url.substring(url.lastIndexOf(".") + 1);
                System.out.println("filePath==:" + filePath);
//            Glide.with(mContext).load(Uri.fromFile(new File(filePath))).into(holder.video_img);
                holder.video_name.setText(mIntegralList.get(i).getFileName());
//            holder.video_time.setText("时长：" + CommonUtils.secToTime(mIntegralList.get(i).getDuration()));
                try {
                    holder.video_size.setText("大小：" + CommonUtils.FormetFileSize(CommonUtils.getFileSize(new File(filePath))));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return view;
        }

        private class ViewHolder {
            ImageView choose_img;
            //            ImageView video_img;
            TextView video_name;
            TextView video_size;
        }

    }

    /**
     * 加载框显示
     **/
    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void buildProgressDialog(boolean cancelable) {
        if (progressDialog == null) {
            AlertDialog.Builder builder = new AlertDialog.Builder(LocalVideoActivity.this);
            builder.setView(R.layout.item_progress_dialog);
            builder.setCancelable(cancelable);
            progressDialog = builder.create();
            progressDialog.show();
        } else {
            progressDialog.show();
        }
    }

    /**
     * 加载框消失
     **/
    public void cancelProgressDialog() {
        if (progressDialog != null) {
            progressDialog.dismiss();
        }
    }
}
